import { Input } from "antd";
import React, { ChangeEvent, FC, useEffect, useState } from "react";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { LIST_SEARCH_PARAM_KEY } from "../../constant";

const { Search } = Input;

const ListSearch: FC = () => {
  const nav = useNavigate()
  const { pathname } = useLocation()
  const [value, setValue] = useState<string>("");

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setValue(event.target.value);
  }
  const [searchParams] = useSearchParams()
  useEffect(() => {
    //每当searchParams有变化就执行
    const newVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ""
    setValue(newVal)
  },[searchParams])
  //点击搜索跳转连接
  function handleSearch(value: string) {
    nav({
      pathname,
      search:`${LIST_SEARCH_PARAM_KEY}=${value}`
    })
  }
  return (
    <Search
      placeholder="输入关键字"
      onSearch={handleSearch}
      onChange={handleChange}
      enterButton
      style={{ width: 200 }}
      allowClear
      value={value}
    />
  );
};

export default ListSearch;
